import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { lastValueFrom } from 'rxjs';
import { Observable } from 'rxjs/internal/Observable';
import { EContractService } from 'src/app/service/business/e-contract.service';
import { CommonService } from 'src/app/service/common/common.service';
import { MessageService } from 'src/app/service/message.service';

@Component({
  selector: 'app-e-contract',
  templateUrl: './e-contract.component.html',
  styleUrls: ['./e-contract.component.scss']
})
export class EContractComponent implements OnInit {

  constructor(
    private http: HttpClient,
    private message: MessageService,
    private eContract: EContractService,
    private common: CommonService
  ) { }

  cols = {
    "funcNo":	"业务编号",
    "funcType":	"业务类型",
    "isCitizen": "居民用水",
    "state": "签署状态",
    "createTime": "合同生成时间",
    "signTime": "签署时间",
  }
  dataSet: any = [];

  state = [
    { value: '未签署', color: 'yellow' },
    { value: '已签署', color: 'green' },
  ];
  funcType = {
    '4': { value: '过户', color: 'green' },
    '11': { value: '大口径报装', color: 'green' },
    '13': { value: '小口径报装', color: 'green' },
  };
  isCitizen = [
    { value: '是' },
    { value: '否' },
  ]

  ngOnInit() {
    this.getContractList();
  }

  getContractList(){
    this.nzLoading = true;
    this.dataSet = []
    this.nzTotal = 0
    this.eContract._getContractList(this.nzPageIndex, this.nzPageSize).subscribe({
      next: (res: any) => {
        if(res && res.resultList && res.resultList.length > 0){
          this.dataSet = res.resultList
          this.nzTotal = res.resultList.length
        }

        this.nzLoading = false;
      },
      error: (error: any) => {
        console.log(error);
        this.nzLoading = false;
      }
    })
  }

  // 查看合同
  nzSpinning = false
  formData = new FormData()
  pdfId = ''
  contractData: any
  modalIsVisible = false;
  okBtnText = ''
  async viewContract(data: any){
    this.contractData = data
    console.log(this.pdfId)
    if(data.fileId && data.fileId !== 'null'){
      this.modalIsVisible = true
      this.okBtnText = '已签署完成'
      this.pdfId = data.fileId
      return 
    }

    this.okBtnText = '签署'
    this.nzSpinning = true
    try{
      const contractParams = await lastValueFrom(this.eContract._getContractParams(data.id))
      if(!contractParams || !contractParams.modelName){
        this.message.error('获取合同模板参数失败，请重试')
        this.nzSpinning = false
        return
      }

      Object.keys(contractParams).forEach(key => {
        this.formData.append(key, contractParams[key])
      })
      this.viewPDF()
    }catch(error){
      this.nzSpinning = false
      this.message.error('生成电子合同失败')
    }
    // let url = `/api/gsxmcp/pb/fm/v1.0/download/${fileId}`;
    // this.pdfId = data.fileId
  }
  // 合同预览
  modalHandleCancel(){
    this.modalIsVisible = false;
  }
  modalHandleOk(text: any){
    if(text === '已签署完成'){
      this.message.success('已签署完成')
      return
    }

    this.modalIsVisible = false;
    this.signVisible = true
  }

  signVisible = false
  sign(e: any){
    this.formData.append('img_syrqm', e)
    this.nzSpinning = true
    this.viewPDF(1)
  }

  async viewPDF(type = 0){
    const pdf: any = await lastValueFrom(this.common._getPDFId(this.formData))
    console.log('pdf', pdf)
    if(pdf && pdf.fileId){
      this.pdfId = pdf.fileId
      if(type === 1){ // 签署合同
        this.updateContract()
      }
    }else{
      this.message.error('生成电子合同失败')
    }
    this.nzSpinning = false
  }
  updateContract(){
    this.eContract._updateContract(this.contractData.id, this.pdfId).subscribe({
      next: (res: any) => {
        console.log(res)
        this.message.successModal('签署成功')
        this.okBtnText = '已签署完成'
        this.getContractList()
      },
      error: error => {
        this.message.createErrorMessage(error)
      }
    })
  }

  // 分页
  resultList = []
  nzLoading = true;
  nzTotal = 2;
  pageSizeOptions = [2, 5, 10, 15, 20, 25]; // 页数选择器
  nzPageSize = 5;
  nzPageIndex = 1;
}
